/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "android.hardware.memtrack@1.0-service-qiku"

#include <log/log.h>

#include <hardware/hardware.h>

#include "Memtrack.h"

namespace android {
namespace hardware {
namespace memtrack {
namespace V1_0 {
namespace implementation {

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
#define min(x, y) ((x) < (y) ? (x) : (y))

Memtrack::Memtrack() {
}

Memtrack::~Memtrack() {}

uint64_t Memtrack::getSizeInBytes(pid_t pid, bool lineType, bool isflag) {
    FILE *fp;
    char line[1024];
    char syspath[128];
    size_t accounted_size = 0;
    size_t unaccounted_size = 0;

    snprintf(syspath, sizeof(syspath), "/d/kgsl/proc/%d/mem", pid);
    fp = fopen(syspath, "r");
    if (fp == NULL) {
        return 0;
    }

    /* Go through each line of <pid>/mem file and for every entry of type "gpumem"
     * check if the gpubuffer entry is usermapped or not. If the entry is usermapped
     * count the entry as accounted else count the entry as unaccounted.
     */
    while (1) {
        unsigned long size, mapsize;
        char line_type[7];
        char flags[10];
        char line_usage[19];
        int ret, egl_surface_count = 0, egl_image_count = 0;
        if (fgets(line, sizeof(line), fp) == NULL) {
            break;
        }

        /* Format:
         *  gpuaddr useraddr     size    id flags       type            usage sglen mapsize eglsrf eglimg
         * 545ba000 545ba000     4096     1 -----pY     gpumem      arraybuffer     1  4096      0      0
         */
        ret = sscanf(line, "%*x %*x %lu %*d %9s %6s %18s %*d %lu %6d %6d\n",
                       &size, flags, line_type, line_usage, &mapsize,
                       &egl_surface_count, &egl_image_count);
        if (ret == 7 && size != 0) {
            if (unaccounted_size + size < size) {
                fclose(fp);
                return 0;
            }

            if (strcmp(line_type, lineType ? "gpumem":"ion") == 0) {
                if (flags[6] == 'Y') {
                    if (accounted_size + mapsize > accounted_size) {
                        accounted_size += mapsize;
                    }
                    if (mapsize > size) {
                        fclose(fp);
                        return 0;
                    }
                    unaccounted_size += size - mapsize;
                } else {
                    unaccounted_size += size;
                }
            } else if (strcmp(line_type, !lineType ? "gpumem":"ion") == 0) {
                if (strcmp(line_usage, "egl_surface") == 0) {
                    unaccounted_size += size;
                }
                else if (egl_surface_count == 0) {
                    unaccounted_size += size / (egl_image_count ? egl_image_count : 1);
                }
            }
        }
    }
    fclose(fp);
    if (isflag && accounted_size != 0) {
        return  accounted_size;
    } else if (!isflag&& unaccounted_size != 0) {
        return unaccounted_size;
    }
    return 0;
}

Return<void> Memtrack::getMemory(int32_t pid, MemtrackType type,
        getMemory_cb _hidl_cb)  {
    std::vector<MemtrackRecord> records;
    if ((type == MemtrackType::GL || type == MemtrackType::GRAPHICS)&& pid > 0) {
        uint64_t accounted_size = 0;
        uint64_t unaccounted_size = 0;
        switch (type) {
            case MemtrackType::GL:
                accounted_size = Memtrack::getSizeInBytes(pid, true, true);
                unaccounted_size = Memtrack::getSizeInBytes(pid, true, false);
                break;
            case MemtrackType::GRAPHICS:
                accounted_size = Memtrack::getSizeInBytes(pid, false, true);
                unaccounted_size = Memtrack::getSizeInBytes(pid, false, false);
                break;
            default:
                break;
            }
        MemtrackRecord accounted_record = {
            .flags = static_cast<uint32_t>(MemtrackFlag::SMAPS_ACCOUNTED),
            .sizeInBytes = accounted_size,
        };
        MemtrackRecord unaccounted_record = {
            .flags = static_cast<uint32_t>(MemtrackFlag::SMAPS_UNACCOUNTED),
            .sizeInBytes = unaccounted_size,
        };
        records.push_back(accounted_record);
        records.push_back(unaccounted_record);
    }
    _hidl_cb(MemtrackStatus::SUCCESS, records);
    return Void();
}

} // namespace implementation
}  // namespace V1_0
}  // namespace memtrack
}  // namespace hardware
}  // namespace android
